package com.qinhailin.portal.dbm.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.qinhailin.common.util.DateUtil;
import com.qinhailin.portal.dbm.model.DTTask;
import com.qinhailin.portal.dbm.po.Data;

/**
 * 接收客户端上报数据
 * @author ward
 */

public class UploadServiceImpl{
	
	@Inject
	private DTQueryServiceImpl queryService;
	@Inject
	private CPGetIDService getIDService;
	@Inject
	private DTTaskServiceImpl taskService;
	private Logger log = Logger.getLogger(this.getClass());
	
	public Integer save(Data data) {
		// data.getJson() MAP<Key,Value>
		// 等等! data被JSON化了, 那么内容就不需要单独JSON化了
		// 在上层ACTION层已经解析了JSON
		Integer rQueryID = data.getRQueryID();
		String tableName = queryService.getTableName(rQueryID);
		List<Map<String, Object>> table = data.getData();
		if(tableName != null && tableName.length() > 0 && table != null && table.size() > 0) {
			List<Record> rs = new ArrayList<>();
			Timestamp now = DateUtil.getCurrentTimestamp();
			DTTask task = this.genTask(data.getRCustID(), now, data.getXType(), data.getRQueryID(), data.getCost(), (Integer)0, data.getXEventTime());
			for(Map<String, Object> t : table) {
				rs.add(new Record().setColumns(t));
			}
			Integer i = 1;
			//序号
			Integer id = getIDService.cp_getid(0, tableName, rs.size());
			
			for(Record r : rs) {
				r.set("sID", id).set("sCreateTime", now).set("sLastUpdate", now).set("sVersion", 1).set("rCust_ID", data.getRCustID());
				if(r.get("xEventTime") == null) {
					r.set("xEventTime", now.getTime());
				}
				i++;
				id ++;
			}
			Db.batchSave(tableName, rs, 100);
			//
			taskService.update(task.setXRowQty(rs.size()).setXSaveCost(Long.valueOf(DateUtil.getCurrentTimestamp().getTime() - now.getTime()).intValue()));
			return rs.size();
		}else {
			// 记录错误
			log.error("保存数据出现异常:客户端返回的数据异常:表名:" + tableName + ",记录行数:" + (table != null ? table.size() : 0));
		}
		return 0;
	}
	
	
	
	protected DTTask genTask(Integer rCustID, Timestamp now, Integer type, Integer rQueryID, Integer cost, Integer qty, Timestamp eventTime) {
		DTTask task = new DTTask()
				.setRCustID(rCustID)
				.setXDateTime(now)
				.setXType(type)
				.setRQueryID(rQueryID)
				.setXCost(cost)
				.setXEventTime(eventTime)
				.setXRowQty(0)
				;
		taskService.save(task);
		return task;
	}

}
